#!/usr/bin/php
<?php
/*
 *   This file is part of verbum.
 *
 *   poat is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   poat is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with poat.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * 	 Copyright (c) 2008 Sergio Gabriel Teves <gabriel.sgt at gmail.com>
 */

require("bashcommon.php");

$starttime=mtime();
$logid = startlog("upstats");
$blog =& LoggerManager::getLogger('bash_updatestats');
$blog->info("Started");
$_log->info("Started");

define('CURRENT_DIR',dirname(__FILE__));
@chdir(CURRENT_DIR);

$last_slash = strrpos(CURRENT_DIR, "/");
$postats = TEMP_PATH."/stats";

DEFINE('SCRIPT',CURRENT_DIR.'/msgstats.sh');
DEFINE('PYSVN',CURRENT_DIR.'/svncontrol.py');

$svnmaxretry=1;

if (!file_exists(TEMP_PATH)) {
	createDir(TEMP_PATH);
}

if (!file_exists($postats)) {
	createDir($postats);
}

if (!file_exists(SVN_LOCATION)) {
	createDir(SVN_LOCATION);
}

function addfile(&$array,$index,$file,$prj,$sprj) {
	$elem = array("file" => $file,"prj" => $prj,"sprj" => $sprj);
	$array->add($index,$elem);
}

//error_reporting(0);
//ini_set('display_errors', false);
$blog->debug("ROOT_PATH: ".ROOT_PATH);
$blog->debug("SVN_ROOT: ".SVN_ROOT);
$blog->debug("SVN_LOCATION: ".SVN_LOCATION);

$totalfiles=0;
$totalprojects=0;
$totalfailedfiles=0;

$blog->info("Processing");
$_log->info("Processing");

/* GET ACTIVE PROJECT LIST */
$prj = new project;
$prj->status=STATUS_ACTIVE;
$prjlist = $loader->loadListBy($prj,$prj->listByStatus(true));

$usernotify = new maplist;
$teamnotify = new maplist;
$proofnotify = new maplist;

foreach ($prjlist as $inprj) {
	$totalprojects+=1;
	$blog->debug("============= PROJECT ".$inprj->id." - ".$inprj->name." =============");
	
	/* GET ACTIVE SUBPROJECT LIST */
	$sprj = new project;
	$sprj->status=STATUS_ACTIVE;
	$sprj->upd="true";
	$sprj->parent=$inprj->id;
	$sprjlist = $loader->loadListBy($sprj,$sprj->listByAny());	

	//debug($sprjlist);
	
	foreach ($sprjlist as $insub) {
		$blog->debug("============= SUBPROJECT ".$insub->id." - ".$insub->name." =============");
		/* GET ACTIVE TEAM LIST */
		$team = new team;
		$teamlist = $loader->loadListBy($team,$team->listByReady($inprj->id,$insub->id,true));
		
		//debug($teamlist);
		
		foreach ($teamlist as $inteam) {
			$blog->debug("============= TEAM ".$inteam->id." - ".$inteam->name. " =============");
			/* GET FILE LIST */
			
			$file = new files($inprj->id);
			$file->teamid=$inteam->id;
			$file->prjid=$insub->id;
			$filelist = $loader->loadListBy($file,$file->loadfiltered());

			if (count($filelist)>0) {
				$url=$inprj->path . str_replace('$LANG',$inteam->lang,$insub->path);
				$svnurl = SVN_ROOT.$url;
				$svnlocation = SVN_LOCATION.$url;
				$svntry=0;
				$ok=false;
				while (!$ok and $svntry<=$svnmaxretry) {
					unset($ar);
					unset($retval);
					$blog->debug("Checkout $svnlocation");
					@exec(PYSVN." ".$svnurl." ".$svnlocation,$ar,$retval);
					if ($retval!=0) {
						switch ( $retval ) {
							case 4:
								$blog->error("Failed retrieving ssl certificate.");
								$_log->error("Failed retrieving ssl certificate.");
								break;
							case 2:
								$blog->error("Unknown error.");
								$_log->error("Unknown error.");
								break;
							default:
								break;
						}
						if (count($ar)>0) {
							$amsg="";
							foreach ($ar as $arm) {
								$amsg.=$arm;
							}
							$blog->error($amsg);
							$_log->error($amsg);
						}
						$blog->debug("Removed: ".deltree($svnlocation));
						$svntry+=1;			
					} else {
						$ok=true;
					}
				}
				if (file_exists($svnlocation)) {
					foreach ($filelist as $infile) {
						$totalfiles+=1;
						$blog->debug("============= FILE ".$infile->id." - ".$infile->name." =============");
						$filename=$svnlocation.'/'.$infile->name;
						
						if (file_exists($filename)) {
							$blog->debug("Processing file ".$filename);	
							
							/* CALL MSGFMT */
							$blog->debug("MSGFMT");
							$in = exec(SCRIPT." ".$filename." ".$postats);				
							/* REMOVE THE FILE */
							//unlink($filename);
							unlink(CURRENT_DIR."/messages.mo");
							/* READ GENERATED STATS */
							$stats = explode(";", $in);
							$blog->debug("Read Stats [".count($stats)."]");
							$notify = false;
							$notify2 = false;
							if (count($stats)==3) {
								$translated=$stats[0];
								$untranslated=$stats[1];
								$fuzzy=$stats[2];
								$control = $fuzzy + $untranslated;
		
								$blog->debug("Old Stats => fuzzy: $infile->fuzzy - untranslated: $infile->untranslated - translated: $infile->translated");
								$blog->debug("Current => fuzzy: $fuzzy - untranslated: $untranslated - translated: $translated");													
								
								/* UPDATE FILE */
								if ($fuzzy > $infile->fuzzy or $untranslated > $infile->untranslated) {
									$notify = true;							
								} else if ($control>0 and ($infile->fuzzy==0 and $infile->untranslated==0)) {
									$notify = true;
								} else if ($control>0 and $fuzzy!=$infile->fuzzy and $untranslated!=$infile->untranslated) {
									$notify2 = true;
								}

								if ($control==0 and ($infile->fuzzy>0 or $infile->untranslated>0) and $infile->statusid == FILE_STATUS_CHKPND) {
									if (!String::isEmpty($infile->userid2)) {
										addfile($proofnotify,$infile->userid2,$infile,$inprj,$insub);	
									}
								}
								
								$infile->translated=$translated;
								$infile->fuzzy=$fuzzy;
								$infile->untranslated=$untranslated;
								$loader->execute($infile->stats());
								
								if (($control > 0 and ($infile->statusid == FILE_STATUS_DONE)) or ($notify2 and $infile->statusid == FILE_STATUS_CHKPND)) {
									$blog->debug("File completed changed.");
									if ($infile->userid!=null and $infile->userid!="") {
										$infile->statusid = FILE_STATUS_LOCKED;
										addfile($usernotify,$infile->userid,$infile,$inprj,$insub);	
									} else if ($infile->userid2!=null and $infile->userid2!="") {
										$infile->statusid = FILE_STATUS_CHKPND;
										addfile($usernotify,$infile->userid2,$infile,$inprj,$insub);
									} else {
										$infile->statusid = FILE_STATUS_TODO;
										//addfile($teamnotify,$infile->teamid,$infile, $inprj,$insub);
									}
									// ALWAYS NOTIFY COORDINATOR
									addfile($teamnotify,$infile->teamid,$infile, $inprj,$insub);
									
									$infile->comment = s("Messages updated from POT",$inteam->lang);
									$infile->stamp=util::hashcode($infile->id);
									$loader->update($infile);
									
									$his = new history($inprj->id);
									$his->statusid=$infile->statusid;
									$his->fileid=$infile->id;
									$his->userid=BOT_USER;
									$his->comment=$infile->comment;
									$his->action=HIS_ACT_ST;
									$loader->save($his);

								} elseif ($notify and ($infile->statusid == FILE_STATUS_TRANS or $infile->statusid == FILE_STATUS_CHKPND)) {
									$blog->debug("Translation phase changed.");
									if ($infile->statusid==FILE_STATUS_CHKPND) {
										if ($infile->userid!=null and $infile->userid!="") {
											$infile->statusid = FILE_STATUS_LOCKED;
										} else {
											if ($infile->userid2!=null and $infile->userid2!="") {
												addfile($usernotify,$infile->userid2,$infile,$inprj,$insub);
											} else {
												$infile->statusid = FILE_STATUS_TODO;	
											}
										}
										$infile->comment = s("Messages updated from POT",$inteam->lang);
										$infile->stamp=util::hashcode($infile->id);
										$loader->update($infile);
									}
									$his = new history($inprj->id);
									$his->statusid=$infile->statusid;
									$his->fileid=$infile->id;
									$his->userid=BOT_USER;
									$his->comment=s("Messages updated from POT",$inteam->lang);
									$his->action=HIS_ACT_ST;
									$loader->save($his);

									if ($infile->userid!=null and $infile->userid!="") {
										addfile($usernotify,$infile->userid,$infile,$inprj,$insub);	
									}// else {
										addfile($teamnotify,$infile->teamid,$infile, $inprj,$insub);
									//}
								} elseif ($notify and $infile->statusid == FILE_STATUS_PROOF) {
									$blog->debug("Proofreading phase changed.");
									
									$his = new history($inprj->id);
									$his->statusid=$infile->statusid;
									$his->fileid=$infile->id;
									$his->userid=BOT_USER;
									$his->comment=s("Messages updated from POT",$inteam->lang);
									$his->action=HIS_ACT_ST;
									$loader->save($his);

									if ($infile->userid!=null and $infile->userid!="") {
										addfile($usernotify,$infile->userid,$infile,$inprj,$insub);	
									}
									if ($infile->userid2!=null and $infile->userid2!="") {
										addfile($usernotify,$infile->userid2,$infile,$inprj,$insub);	
									}// else {
										addfile($teamnotify,$infile->teamid,$infile, $inprj,$insub);
									//}	
								} elseif ($notify){
									addfile($teamnotify,$infile->teamid,$infile, $inprj,$insub);
								}
								$blog->debug("============= FINISHED FILE ".$infile->name. " =============");						
							} else {
								$totalfailedfiles+=1;
								$blog->warn("FAILED PROCESSING STATS ".$infile->name);
							}
						} else {
							$totalfailedfiles+=1;
							$blog->warn("File doesn't exists: ".$infile->name);
						}
					}					
				} else {
					$blog->warn("Couldn't check out");
				}
			} else {
				$blog->debug("Nothing to do.");
			}			
			$blog->debug("============= FINISHED TEAM ".$inteam->id." =============");
		}
		$blog->debug("============= FINISHED SUBPROJECT ".$insub->id." =============");	
	}

	/* UPDATE PROJECT */
	$blog->debug("============= FINISHED PROJECT ".$inprj->id." =============");
	$inprj->statsupdated=util::now();
	$loader->execute($inprj->stats());	

}

if (DISABLE_STATS_NOTIFY != "true") {
	$blog->info("Notify coordinators [".$teamnotify->size()."]");
	$_log->info("Notify coordinators [".$teamnotify->size()."]");

	$blog->info("Notify users [".$usernotify->size()."]");
	$_log->info("Notify users [".$usernotify->size()."]");

	$blog->info("Notify proofreaders [".$proofnotify->size()."]");
	$_log->info("Notify proofreaders [".$proofnotify->size()."]");

	foreach ($teamnotify->getAll() as $teamid => $elems) {
		$u = new user;
		$u->teamid=$teamid;
		$u->groupid=GROUP_COORD;
		$u->status=STATUS_ACTIVE;
		$list = $loader->loadListBy($u,$u->listByFilters());
		
		foreach ($list as $user) {
			//mailNotifyStatUpdate($user,$elems);
			$usernotify->addAll($user->userid,$elems);	
		}
	}
	
	foreach ($usernotify->getAll() as $userid => $elems) {
		$u = new user;
		$u->userid=$userid;
		if ($loader->get($u)) {
			mailNotifyStatUpdate($u,$elems);	
		}
	}
	
	foreach ($proofnotify->getAll() as $userid => $elems) {
		$u = new user;
		$u->userid=$userid;
		if ($loader->get($u)) {
			mailFileTranslated($u,$elems);	
		}
	}
	
} else {
	$blog->info("Notification disabled");
	$_log->info("Notification disabled");
}

endlog($logid);
$db->close();
$endtime=mtime();
$blog->info("Finished");
$_log->info("Finished");
$blog->info("============= * =============");
$_log->info("============= * =============");
$statstext = "Projects processed: ".$totalprojects."\nFiles processed: ".$totalfiles." of which ".$totalfailedfiles." failed.";
$blog->info($statstext);
$_log->info($statstext);
$blog->info("Process time: ".sec2hms($endtime-$starttime,true));
$_log->info("Process time: ".sec2hms($endtime-$starttime,true));
LoggerManager::shutdown();
?>